package com.kexio.log.analytics.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import com.kexio.log.analytics.adapter.PerformanceMonitorAdapter.TraceSpan;
import com.kexio.log.analytics.service.PerformanceAnalyzer;

/**
 * 性能分析器实现
 * 
 * @author Kexio Team
 * @since 1.0.0
 */
@Service
@ConditionalOnProperty(prefix = "kexio.log.analytics", name = "enabled", havingValue = "true")
public class PerformanceAnalyzerImpl implements PerformanceAnalyzer {
    
    private static final Logger logger = LoggerFactory.getLogger(PerformanceAnalyzerImpl.class);
    
    @Override
    public void analyzeMethodPerformance(String className, String methodName, String layer,
                                        long executionTime, boolean isSuccess, Throwable exception,
                                        long memoryUsage) {
        try {
            // 性能分析逻辑
            if (executionTime > 5000) { // 超过5秒的方法
                logger.warn("发现极慢方法: {}.{} [{}] - {}ms, 内存: {}bytes", 
                           className, methodName, layer, executionTime, memoryUsage);
            }
            
            if (!isSuccess && exception != null) {
                logger.debug("方法执行异常: {}.{} - {}", 
                            className, methodName, exception.getClass().getSimpleName());
            }
            
            // 内存使用分析
            if (memoryUsage > 100 * 1024 * 1024) { // 超过100MB
                logger.warn("方法内存使用过高: {}.{} - {}MB", 
                           className, methodName, memoryUsage / (1024 * 1024));
            }
            
        } catch (Exception e) {
            logger.error("分析方法性能失败: {}", e.getMessage(), e);
        }
    }
    
    @Override
    public void analyzeSystemMetrics(double cpuUsage, long memoryUsage, long freeMemory, int activeThreads) {
        try {
            // 系统资源分析
            if (cpuUsage > 90) {
                logger.warn("CPU使用率过高: {}%", cpuUsage);
            }
            
            double memoryUsagePercent = (double) memoryUsage / (memoryUsage + freeMemory) * 100;
            if (memoryUsagePercent > 90) {
                logger.warn("内存使用率过高: {:.2f}%", memoryUsagePercent);
            }
            
            if (activeThreads > 200) {
                logger.warn("活跃线程数过多: {}", activeThreads);
            }
            
        } catch (Exception e) {
            logger.error("分析系统指标失败: {}", e.getMessage(), e);
        }
    }
    
    @Override
    public void analyzeRequestTrace(String traceId, List<TraceSpan> spans) {
        try {
            if (spans == null || spans.isEmpty()) {
                return;
            }
            
            // 分析调用链性能
            long totalDuration = spans.stream().mapToLong(TraceSpan::getDuration).sum();
            TraceSpan slowestSpan = spans.stream()
                .max((s1, s2) -> Long.compare(s1.getDuration(), s2.getDuration()))
                .orElse(null);
            
            if (totalDuration > 10000) { // 超过10秒的调用链
                logger.warn("发现慢调用链: traceId={}, 总耗时={}ms, 节点数={}", 
                           traceId, totalDuration, spans.size());
                
                if (slowestSpan != null) {
                    logger.warn("最慢节点: {} - {}ms", 
                               slowestSpan.getOperationName(), slowestSpan.getDuration());
                }
            }
            
            // 分析异常的调用模式
            if (spans.size() > 50) { // 调用链节点过多
                logger.warn("调用链过于复杂: traceId={}, 节点数={}", traceId, spans.size());
            }
            
        } catch (Exception e) {
            logger.error("分析请求链路失败: {}", e.getMessage(), e);
        }
    }
}
